/**
* ...
* @author Default
* @version 0.1
*/

package bdz.particles{
	import bdz.particles.unit.particle;
	import flash.display.*;
	import flash.geom.Rectangle;

	public class SimpleField{
		private var gravity:Number;
		private var friction:Number;
		private var _bounds:Rectangle;
		private var particles:Array;
		private var negative:Number = -1;
		private var scope:*;
		private var minDist:Number = 50;
		private var springAmount:Number = .00001;
		function SimpleField(gr:Number, fr:Number, sc:*):void {
			gravity = gr;
			friction = fr;
			particles = new Array();
			scope = sc;
		}
		public function set bounds(rect:Rectangle):void {
			_bounds = rect;
		}
		public function addParticle(p:particle):void {
			particles.push(p);
		}
		private function spring(partA:particle, partB:particle):void{
			var dx:Number = scope.mouseX - partA.x;
			var dy:Number = scope.mouseY - partA.y;
			var ax:Number = dx * springAmount;
			var ay:Number = dy * springAmount;
			var dist:Number = Math.sqrt(dx * dx + dy * dy);
			if (dist < minDist) {
				partA.vx += ax / partA.mass;
				partA.vy += ay / partA.mass;
				partB.vx -= ax / partB.mass;
				partB.vy -= ay / partB.mass;
			}
			
		}
		private function attract(partA:particle, partB:particle):void {
			
			var dx:Number = partB.x - partA.x;
			var dy:Number = partB.y - partA.y;
			var distSQ:Number = dx * dx + dy * dy;
			var dist:Number = Math.sqrt(distSQ);
			var force:Number = partA.mass * 10 / distSQ;
			var ax:Number = force * dx / dist;
			var ay:Number = force * dy / dist;
			
			partA.vx += ax / partA.mass;
			partA.vy += ay / partA.mass;
			partB.vx -= ax / partB.mass;
			partB.vy -= ay / partB.mass;
			
			
		}
		public function run():void {
			for each(var p:particle in particles) {
				if (p.x + p.width > _bounds.right || p.x - p.width < _bounds.left) {
					p.vx *= negative;
				}
				if (p.y + p.height > _bounds.bottom || p.y - p.height < _bounds.top) {
					p.vy *= negative;
				}
				p.x += p.vx;
				p.y += p.vy;
			}
			for each(var p1:particle in particles) {
				
				for each(var p2:particle in particles) {
					if (p2.name != p1.name) {
						attract(p1, p2);
						//spring(p1, p2);
					}
				}
			}
		}
	}
	
}